initSession_ID();// 初始化session_id
// var PAGE_INDEX = 1
var PAGE_INDEX = 1, //分页码
    off_on = false, //分页开关(滚动加载方法 1 中用的)
    timers = null; //定时器(滚动加载方法 2 中用的)
var filtVal = -1;
var topTabbarOrder = 0; //顶部栏按钮序号
var orderParams = {}; //订单操作相关参数
$(document).ready(function () {
    loadOrderList(); //初始化订单列表
});
//加载订单列表
function loadOrderList() {
    if(topTabbarOrder == 0) {
        var path = "order/list";
        var params = {
            "SESSION_ID":SESSION_ID,
            "FILTER": filtVal,
            "PAGE_CAPACITY":10,
            "PAGE_INDEX":PAGE_INDEX
        }
    } else {
        var path = "user/code/list";
        var params = {
            "SESSION_ID":SESSION_ID,
            "STATE": filtVal,
            "PAGE_CAPACITY":10,
            "PAGE_INDEX":PAGE_INDEX
        }
    }
    request(path,params,loadOrders);
}
function orderStatusShow(params) {
    var payMoney = params.orderfee == "shareOrder" ? "好友的分享单" : ("实付：" + params.orderfee + "元");
    //根据请求数据展示  模拟数据 0 等待制作， 1制作中， 2 制作完成 ,默认已分享,
    var namePrice = params.sku_name + '<span id="orderFee" class="order-fee">'+ payMoney +'</span>';
    $("#orderNo").text(params.ORDER_ID);
    $("#sku_name").html(namePrice); //意式浓缩<span class="order-fee">实付：<span id="orderFee">7.00元</span></span>
    $("#make_order_time").text(params.time);
    // $("#order_sku_img").attr("src",params.img_path); //图片可用时恢复
    $("#order_sku_img").attr("src","../assets/img/img_01yishi.png"); //图片可用时删除
    $(".order-img").css({"background":'url("../assets/img/circle.png") no-repeat',"background-size":"100%"});
}
function loadOrders(res) {
    var orderHtml =
       `<div class="order-list %s %s" onclick="selectedOrder('%s','%s','%s','%s','%s','%s','%s',this)">\
            <span class="list-order-time">%s</span><span class="list-order-name">%s</span><span class="list-order-status">%s</span>\
       </div>`;
    console.log(res);
    if(!res.BODY.LIST){
        $(".list-title").hide();
    }
    if(PAGE_INDEX == 1 && res.BODY.COUNT == 0) {
        // 为空显示默认
        $("#orderNo").text("******************");
        $("#make_order_time").text("******************");
        $("#sku_name").html("");
        $(".order-status").text("");
        $(".order-img").css({"background":'url("../assets/img/default_circle.png") no-repeat',"background-size":"100%"});
        $("#order_sku_img").attr("src","../assets/img/cupempty-Assistor.png");
        $("#operate").attr("disabled",true).css({"background":"#c1c1c1","color":"#fff"}).text("没有订单");
        $("#operate1").attr("disabled",true).css({"background":"#c1c1c1","color":"#fff"}).text("没有订单");
        $(".apply-refund").css("display","none");
        $(".content").empty();
    }
    if(topTabbarOrder == 0) {  //不同的接口
        _.each(res.BODY.LIST,function (item, index) {
            var SKU_NAME = item.STORE_ORDER[0].SKU_LIST[0].SKU_NAME;
            var borderStyle = (PAGE_INDEX == 1 && index == 0) ? "list-first" : "";
            var selected = (PAGE_INDEX == 1 && index == 0) ? "selected-status" : "";
            var time = item.CREATE_TIME;
            time = time.substring(0,time.length-2);
            var date = time.split(" ")[0]
            var ORDER_ID = item.ORDER_ID;
            var SKU_ID = item.STORE_ORDER[0].SKU_LIST[0].SKU_ID;
            var statusDescrip = "待支付";
            var img_path = item.STORE_ORDER[0].SKU_LIST[0].SKU_PIC;
            var code = "";
            var orderfee = item.PAY_FEE.toFixed(2);
            if(PAGE_INDEX == 1 && index == 0) {
                $(".content").empty();
                orderParams = {
                    "sku_name":SKU_NAME,
                    "time":time,
                    "ORDER_ID":ORDER_ID,
                    "SKU_ID":SKU_ID,
                    "img_path":img_path,
                    "CODE":code,
                    "orderfee":orderfee
                };
                orderStatusShow(orderParams);
            }
            $(".content").append(sprintf(orderHtml,borderStyle,selected,ORDER_ID,SKU_ID,SKU_NAME,time,code,img_path,orderfee,date,SKU_NAME,statusDescrip));
            off_on = true; //[重要]这是使用了 {滚动加载方法1}  时 用到的 ！！！[如果用  滚动加载方法1 时：off_on 在这里不设 true的话， 下次就没法加载了哦！]
        });
    } else {
        _.each(res.BODY.LIST,function (item, index) {
            var SKU_NAME = item.GOODS;
            var borderStyle = (PAGE_INDEX == 1 && index == 0) ? "list-first" : "";
            var selected = (PAGE_INDEX == 1 && index == 0) ? "selected-status" : "";
            var time = item.GET_TIME;
            var date = time.split(" ")[0]
            var ORDER_ID = item.ORDER_NO;
            var SKU_ID = "";
            var statusDescrip = topTabbarOrder == 1 ? "待制作" : "已完成";
            var img_path = item.PIC;
            var code = item.CODE;
            var orderfee = "";
            if(PAGE_INDEX == 1 && index == 0) {
                $(".content").empty();
                if(topTabbarOrder != 0) {
                    var queryPath = "order/query";
                    var queryParams = {
                        "SESSION_ID":SESSION_ID,
                        "ORDER_ID":ORDER_ID
                    };
                    request(queryPath,queryParams,function (res) {
                        var flg = /^0+$/ig.test(res.RSPCD); //全零true
                        // if(flg) {
                            orderParams = {
                                "sku_name":SKU_NAME,
                                "time":time,
                                "ORDER_ID":ORDER_ID,
                                "SKU_ID":SKU_ID,
                                "img_path":img_path,
                                "CODE":code,
                                "orderfee": flg ? res.BODY.PAY_FEE.toFixed(2) : "shareOrder"
                            };
                            orderStatusShow(orderParams);
                        // }
                    })
                }
            }
            $(".content").append(sprintf(orderHtml,borderStyle,selected,ORDER_ID,SKU_ID,SKU_NAME,time,code,img_path,orderfee,date,SKU_NAME,statusDescrip));
            off_on = true; //[重要]这是使用了 {滚动加载方法1}  时 用到的 ！！！[如果用  滚动加载方法1 时：off_on 在这里不设 true的话， 下次就没法加载了哦！]
        });
    }
    PAGE_INDEX++;  //请求成功下次加载页码加1
}
function selectedOrder(orderid,skuid,sku_name,time,code,img_path,orderfee,dom) {
    if(topTabbarOrder != 0) {
        var queryPath = "order/query";
        var queryParams = {
            "SESSION_ID":SESSION_ID,
            "ORDER_ID":orderid
        };
        request(queryPath,queryParams,function (res) {
            var flg = /^0+$/ig.test(res.RSPCD); //全零true
                orderParams = {
                    "sku_name":sku_name,
                    "time":time,
                    "ORDER_ID":orderid,
                    "SKU_ID":skuid,
                    "img_path":img_path,
                    "CODE":code,
                    "orderfee": flg ? res.BODY.PAY_FEE.toFixed(2) : "shareOrder"
                };
                orderStatusShow(orderParams);
        })
    } else {
        orderParams = {
            "sku_name":sku_name,
            "time":time,
            "ORDER_ID":orderid,
            "SKU_ID":skuid,
            "img_path":img_path,
            "CODE":code,
            "orderfee":orderfee
        };
        orderStatusShow(orderParams);
    }

    $(".selected-status").removeClass("selected-status");
    $(dom).addClass("selected-status");
};
//下拉加载
$('.page').scroll(function() {
    //当时滚动条离底部60px时开始加载下一页的内容
    if (($(this)[0].scrollTop + $(this).height() + 60) >= $(this)[0].scrollHeight) {
        //这里用 [ off_on ] 来控制是否加载 （这样就解决了 当上页的条件满足时，一下子加载多次的问题啦）
        if (off_on) {
            off_on = false;
            //page++;
            console.log("第"+PAGE_INDEX+"页");
            loadOrderList();  //调用执行上面的加载方法
        }
    }
});

/*
$(".page").scroll(function() {
    //当时滚动条离底部60px时开始加载下一页的内容
    if (($(window).height() + $(window).scrollTop() + 60) >= $(document).height()) {
        clearTimeout(timers);
        timers = setTimeout(function() {
            // page++;
            console.log("第" + PAGE_INDEX + "页");
            pullDownLoad();
        }, 300);
    }
});
*/


$(".topTabbar li").on("tap",function (e) {
    $(".topTabbar").find(".active-tapbar").removeClass("active-tapbar");
    $(this).addClass("active-tapbar");
    topTabbarOrder = Number(e.currentTarget.attributes.order.value);
    if(topTabbarOrder == 0) {
        filtVal = -1; //未付款
        PAGE_INDEX = 1;
        $(".order-status").text("等待支付");
        $("#operate").removeAttr("disabled").css({"background":"#008065","display":"block"}).text("立即支付");
        $(".apply-refund").css("display","none");
        $("#operate1").css("display","none");
        $(".list-title").show();
    } else if(topTabbarOrder == 1) { //提货码列表接口
        filtVal = 1;  //1：未使用
        PAGE_INDEX = 1;
        $(".order-status").text("等待制作");
        $("#operate").removeAttr("disabled").css({"background":"#008065","display":"block"}).text("去制作咖啡");
        $(".apply-refund").css("display","block");
        $("#operate1").css("display","none");
        $(".list-title").show();
    } else {  //提货码列表接口
        filtVal = 2; //2.已失效（已使用，已冻结，已过期
        PAGE_INDEX = 1;
        $(".order-status").text("已完成");
        $(".apply-refund").css("display","none");
        $("#operate").css("display","none");
        $("#operate1").removeAttr("disabled").css({"background":"#008065","display":"block"}).text("评价一下");
        $(".list-title").show();
    }
    loadOrderList();
});
//支付&制作
$("#operate").on("tap",function () {
    if(topTabbarOrder == 0) {
        var payPath = "order/payment";
        var payParams = {
            "SESSION_ID":SESSION_ID,
            "ORDER_ID":orderParams.ORDER_ID,
            "PAYMENT":"WXJSPAY"
        }
        request(payPath,payParams,function (res) {
            //自提咖啡支付
            var flg = /^0+$/ig.test(res.RSPCD); //全零true
            if(!flg) return showErroMsg("支付失败,返回首页！",function () {
                window.location.replace("./index.html");
            });
            var appId = RegBetween(res.BODY.PAYMENT_STR,"appId=","&timeStamp=");
            var timestamp = RegBetween(res.BODY.PAYMENT_STR,"timeStamp=","&signType=");
            var nonceStr = RegBetween(res.BODY.PAYMENT_STR,"nonceStr=","&paySign=");
            var package = RegBetween(res.BODY.PAYMENT_STR,"package=","&nonceStr=");
            var signType = RegBetween(res.BODY.PAYMENT_STR,"signType=","&package=");
            var paySign = RegBetween(res.BODY.PAYMENT_STR,"paySign=","");
            onBridgeReady(appId,timestamp,nonceStr,package,signType,paySign,function (res) {
                location.replace("./order_make.html?order_id="+res.BODY.ORDER_ID);
            });
        });
    } else if(topTabbarOrder == 1) {
        var OP_NUM = sessionStorage.getItem("machCode");
        if(OP_NUM) {
            location.replace("./order_make.html?order_id="+orderParams.ORDER_ID);
        } else {
            showErroMsg("扫描咖啡机屏幕上的二维码，制作咖啡！",function () {
                wx.scanQRCode({
                    needResult: 1,
                    desc: '请扫描机身二维码',
                    scanType: ["qrCode","barCode"],//一维码、二维码
                    success: function (res) {
                        // alert(JSON.stringify(res))
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果

                        var r = result.match(/machCode=(\S*)/)[1]; //匹配目标参数
                        if (r != null) {
                            OP_NUM = r.split("$")[1];
                            sessionStorage.setItem("machCode",r.split("$")[1]);
                            location.replace("./order_make.html?order_id="+orderParams.ORDER_ID);
                        } else {
                            return showErroMsg("扫码失败，请重新扫描！",function(){
                $(".showErrorMassage").remove();
            })
                        }
                    },
                    error: function(res){
                        if(res.errMsg.indexOf('function_not_exist') > 0){
                            alert('版本过低请升级')
                        }
                    }
                });
            },false)
        }
    }
});
//退款
$("#aplyRefund").on("tap",function () {
    var today = getNowFormatDate();
    var orderDate = orderParams.time.split(" ")[0];
    if(today != orderDate) return showErroMsg("只能退款当天的订单!<br><span style='font-size:8px;'>订单时间：" +orderDate + "</span>",function () {
        $(".showErrorMassage").remove();
    });
    showErroMsg("是否确定申请退款？",function () {
        //订单查询
        var orderQueryPath = "order/query";
        var orderQueryParams = {
            "SESSION_ID":SESSION_ID,
            "ORDER_ID":orderParams.ORDER_ID
        }
        request(orderQueryPath,orderQueryParams,function (res) {
            if(res.RSPCD == "ORDER10028") {
                location.href = "./replay_refund_error.html";
            }
            //申请退款
            var refundPath = "refund/applicate";
            var refundParams = {
                "SESSION_ID":SESSION_ID,
                "ORDER_ID":orderParams.ORDER_ID,
                "SKU_ID":res.BODY.STORE_ORDER[0].SKU_LIST[0].SKU_ID,
                "REFUND_TYPE":1,
                "REFUND_FEE":res.BODY.STORE_ORDER[0].SKU_LIST[0].REFUNDABLE_FEE,
                "REASON":"制作出错",
                "MEMO":"立即退款",
                "PICS":[]
            }
            request(refundPath,refundParams,function (res) {
                if(res.RSPCD == "ORDER10001") {
                    showErroMsg("订单号不存在！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10034") {
                    showErroMsg("订单未付款！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10028") {
                    showErroMsg("订单与用户不匹配！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10027") {
                    showErroMsg("商品与订单不匹配！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10035") {
                    showErroMsg("商品已退款！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10032") {
                    showErroMsg("超出可退款限额！",function(){
                $(".showErrorMassage").remove();
            });
                } else if(res.RSPCD == "ORDER10032") {
                    showErroMsg("重复申请退款！",function(){
                $(".showErrorMassage").remove();
            });
                } else {
                    location.replace('./report_errors_success.html');
                }
            })

        })
    })
})
//去评价
$("#operate1").on("click",function () {
    location.href = "./feedback.html";
})
/*
window.addEventListener('touchmove', function (e) {
    if(boxIsShow) {
        e.preventDefault();
    }
    }, false);*/
